/*
 * @Author: your name
 * @Date: 2022-03-14 17:08:54
 * @LastEditTime: 2022-04-03 20:15:04
 * @LastEditors: Please set LastEditors
 * @Description: 文件标签管理
 * @FilePath: \blog-system-front\src\Pages\Article\article_caterory\index.js
 */

import { Button, Modal, Table, Form, notification, Input } from "antd";
import React, { useEffect, useState, useRef, useContext } from "react";
import ContentHeader from "@/Containers/ContentHeader";
import Main from "@/Containers/main";
import request from "@/api";
import AddModal from "./addModal";
import { deleteCategory } from "@/Services/article";
import FilterForn from "./FilterForn";
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  let childNode = children;
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };
  const save = async (e) => {
    
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record,...values });
    } catch (errInfo) {
      console.log("Save failed:", errInfo);
    }
  };
  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `${title} is required.`,
          },
        ]}
      >
        <Input ref={inputRef} onBlur={save} onPressEnter={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={() => toggleEdit()}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};
export default function ArticleCategory() {
  const [dataSoure, setDataSource] = useState([]);
  const [isModalVisible, setisModalVisible] = useState(false);
  const [record, setRecord] = useState([{}]);
  const [selectRowkeys, setSelectRowkeys] = useState([]);
  const [category, setCategory] = useState([]);
  const [form] = Form.useForm();
  const [status, setStatus] = useState("new");
  const columns = [
    {
      title: "标签名称",
      dataIndex: "category_name",
      key: "category_name",
      editable: true,
    },
    {
      title: "文章数量",
      dataIndex: "category_count",
      key: "category_count",
    },
    {
      title: "操作",
      key: "operation",
      render: (text, record) => {
        return <a onClick={() => handleUpdate(record)}>编辑</a>;
      },
    },
  ];
  useEffect(() => {
    initData();
  }, []);

  const deleteNullItem = (data) => {
    return data.map((d) => {
      if (d.children.length !== 0) {
        deleteNullItem(d.children);
        return d;
      }
      delete d.children;
      return d;
    });
  };
  const handleUpdate = (record) => {
    setRecord([record]);
    setStatus("edit")
    setisModalVisible(true);
  };
  const renderChildren = (data, item) => {
    const renderData = [];
    const children = data.filter((n) => n.parentId === item.category_id);
    if (children.length !== 0) {
      children.forEach((d) =>
        renderData.push({
          ...d,
          children: renderChildren(data, d),
        })
      );
    }

    return renderData;
  };
  const handleSave = (row) => {
    const newData = [...dataSoure];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setDataSource(newData);
  };

  /**
   * @description: 初始化应用数据
   * @param {*}
   * @return {*}
   */
  const initData = (params) => {
    request({
      url: "v1/article/category",
      method: "GET",
      params,
    }).then((res) => {
      const { content } = res;
      const array = [];
      content.forEach((item) => {
        if (item.isTopLevel === 1) {
          array.push({
            ...item,
            children: renderChildren(content, item),
          });
        }
      });

      const data = deleteNullItem(array);
      setDataSource(data);

      setCategory(array);
    });
  };
  const handleNewBuild = () => {
    setStatus("new")
    setRecord([]);
    setisModalVisible(true);
  };
  const handleCancel = () => {
    setisModalVisible(false);
  };
  /**
   * @description: 保存标签
   * @param {*}
   * @return {*}
   */
  const saveCategorys = () => {
    form.validateFields().then((values) => {
      request({
        url: "/v1/article/category/save",
        method: "POST",
        data: values,
      }).then((res) => {
        if (!res.failed) {
          notification.success({
            message: res.message,
          });
          setisModalVisible(false);
          initData();
        }
      });
    });
  };
  /**
   * @description: 表格勾选回调
   * @param {*}
   * @return {*}
   */
  const rowSelection = {
    onChange: (selectedRowKey) => {
      setSelectRowkeys(selectedRowKey);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      setSelectRowkeys(selectedRows);
    },
  };
  /**
   * @description: 数据删除
   * @param {*}
   * @return {*}
   */
  const handleDelete = () => {
    deleteCategory(selectRowkeys).then((res) => {
      if (!res.failed) {
        initData();
      }
    });
  };
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };
  const column = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave: handleSave,
      }),
    };
  });
  return (
    <>
      <ContentHeader title="标签管理">
        <Button type="primary" onClick={handleNewBuild}>
          新建
        </Button>
        <Button
          type="primary"
          onClick={handleDelete}
          style={{ marginRight: 10 }}
          disabled={selectRowkeys.length === 0}
        >
          删除
        </Button>
      </ContentHeader>
      <Main>
        {/* <FilterForn initData={initData}></FilterForn> */}
        <Table
          dataSource={dataSoure}
          columns={column}
          bordered
          rowKey="category_id"
          rowSelection={{
            type: "checkbox",
            ...rowSelection,
          }}
          pagination={false}
        ></Table>
        <Modal
          destroyOnClose
          title="新建"
          visible={isModalVisible}
          onOk={saveCategorys}
          onCancel={handleCancel}
        >
          <AddModal
            form={form}
            status={status}
            category={category}
            record={record}
          />
        </Modal>
      </Main>
    </>
  );
}
